package com.coco.user.service.impl;

import com.coco.common.constant.Constant;
import com.coco.common.constant.LoginEnum;
import com.coco.common.result.CommonResponse;
import com.coco.common.result.ResultData;
import com.coco.common.util.TokenUtil;
import com.coco.user.mapper.UserMapper;
import com.coco.user.pojo.TbUser;
import com.coco.user.service.UserService;
import com.coco.user.vo.UserLoginVo;
import com.coco.user.vo.UserRegisterVo;
import com.coco.user.vo.UserSearchVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private TokenUtil tokenUtil;

    /**
     * 查询所有用户
     *
     * @return
     * @author hu
     * @date 2021/7/21 20:53
     */
    @Override
    public List<TbUser> userList() {
        return userMapper.userList();
    }

    /**
     * 添加用户信息
     * @param user
     * @return
     * @author hu
     * @date 2021/7/21 20:53
     */
    @Override
    public void add(TbUser user) {
        user.setCreateTime(new Date());
        userMapper.add(user);
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     * @author hu
     * @date 2021/7/21 20:53
     */
    @Override
    public void update(TbUser user) {
        userMapper.update(user);
    }

    @Override
    public void deleteById(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public TbUser findOne(Long id) {
        return userMapper.findOne(id);
    }

    @Override
    public ResultData findAllSearch(UserSearchVo userSearchVo) {
        PageHelper.startPage(userSearchVo.getPage(),userSearchVo.getLimit());
        List<UserSearchVo> userList = userMapper.findAllSearch(userSearchVo);
        PageInfo<UserSearchVo> pageInfo = new PageInfo<>(userList);
        return new ResultData(pageInfo.getList(),pageInfo.getTotal());
    }

    @Override
    public CommonResponse register(UserRegisterVo userRegisterVo) {
        String rediscode = (String) redisTemplate.opsForValue().get(Constant.AdminRegisterConstant.PRE_CODE + userRegisterVo.getPhone());
        TbUser user = userMapper.findOneByName(userRegisterVo.getUserName());
        if (user==null){
            if (rediscode!=null){
                if (userRegisterVo.getCode().equals(rediscode)){
                    //删除验证码
                    redisTemplate.delete(Constant.AdminRegisterConstant.PRE_CODE+userRegisterVo.getPhone());
                    //验证码通过
                    Date date = new Date();
                    userRegisterVo.setCreateTime(date);
                    userMapper.register(userRegisterVo);
                    rabbitTemplate.convertAndSend("email",userRegisterVo.getEmail());
                    return new CommonResponse(Constant.AdminRegisterConstant.ADMIN_REGISTER,Constant.AdminRegisterConstant.ADMIN_REGISTER_MESSAGE);
                }else {
                    //验证不通过
                    return new CommonResponse(Constant.AdminRegisterConstant.ADMIN_YZM,Constant.AdminRegisterConstant.ADMIN_YZM_MESSAGE);
                }
            }else {
                return new CommonResponse(Constant.AdminRegisterConstant.USER_LOGUIN_ERRON,Constant.AdminRegisterConstant.USER_LOGUIN_EMESSAGE);
            }
        }
        //有用户名重复
        return new CommonResponse(Constant.AdminRegisterConstant.ADMIN_EXIST,Constant.AdminRegisterConstant.ADMIN_EXIST_MESSAGE);
    }

    /**
     * 发送验证码
     * @param phone
     */
    @Override
    public void getCode(String phone) {
        String code = createCode();
        System.out.println(Constant.AdminRegisterConstant.PRE_CODE+phone);
        redisTemplate.opsForValue().set(Constant.AdminRegisterConstant.PRE_CODE+phone, code,5, TimeUnit.MINUTES);
        HashMap<String, String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("code",code);
        rabbitTemplate.convertAndSend("coco",map);
    }

    /**
     * 用户登录
     * @param loginVo
     * @return
     */
    @Override
    public CommonResponse dologin(UserLoginVo loginVo) {
        //判断用户名或密码是否为空
        if (!StringUtils.isEmpty(loginVo.getPhone()) && !StringUtils.isEmpty(loginVo.getPassword())){
            //通过手机号查询用户信息
            TbUser admin = userMapper.findUserByPhone(loginVo.getPhone());
            //判断用户是否登陆成功
            if (admin!=null && loginVo.getPassword().equals(admin.getPassword())){
                Map<String, String> token = tokenUtil.getToken(admin.getPhone(), loginVo.getType());
                return new CommonResponse(LoginEnum.LOGIN_SUCCESS.getCode(),LoginEnum.LOGIN_SUCCESS.getMessage(),token);
            }
            return new CommonResponse(LoginEnum.LOGIN_FAIL.getCode(),LoginEnum.LOGIN_FAIL.getMessage());
        }
        return new CommonResponse(LoginEnum.LOGIN_MSG_ERROR.getCode(), LoginEnum.LOGIN_MSG_ERROR.getMessage());

    }

    /**
     * 创建验证码
     * @return
     */
    private String createCode(){
        Random random = new Random();
        int i = random.nextInt(Constant.AdminRegisterConstant.ADMIN_CODE_LENTH);
        if (i<Constant.AdminRegisterConstant.ADMIN_ONE_NUM){
            i=i*Constant.AdminRegisterConstant.ADMIN_THREE_NUM;
        }else if (i<Constant.AdminRegisterConstant.ADMIN_TWO_NUM){
            i=i*Constant.AdminRegisterConstant.ADMIN_TWO_NUM;
        }else if (i<Constant.AdminRegisterConstant.ADMIN_THREE_NUM){
            i=i*Constant.AdminRegisterConstant.ADMIN_ONE_NUM;
        }
        return i+Constant.AdminRegisterConstant.ADMIN_THREE_NULL;
    }


}
